package   com.stars.home.update.util

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import com.stars.home.App
import java.text.DecimalFormat

object Utils {
    /**
     * 获取应用程序名称
     */
    @Synchronized
    fun getAppName(context: Context): String? {
        try {
            val packageManager = context.packageManager
            val packageInfo = packageManager.getPackageInfo(
                context.packageName, 0
            )
            val labelRes = packageInfo.applicationInfo.labelRes
            return context.resources.getString(labelRes)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }

    /**
     * 获取包名
     */
    fun getPackageName(): String? {
        return App.getApp()?.packageName
    }

    fun jumpToAppSetting(context: Activity) {
        jumpToAppSetting(context, -1)
    }

    fun jumpToAppSetting(context: Activity, requestCode: Int) {
        //手机厂商
//        String brand = Build.BRAND;
//        if (TextUtils.equals(brand.toLowerCase(), "redmi") || TextUtils.equals(brand.toLowerCase(), "xiaomi")) {
//            gotoMiuiPermission(context,requestCode);
//        } else if (TextUtils.equals(brand.toLowerCase(), "meizu")) {
//            gotoMeizuPermission(context,requestCode);
//        } else if (TextUtils.equals(brand.toLowerCase(), "huawei") || TextUtils.equals(brand.toLowerCase(), "honor")) {
//            gotoHuaweiPermission(context,requestCode);
//        } else {
        if (requestCode > -1) {
            context.startActivityForResult(
                getAppDetailSettingIntent(),
                requestCode
            )
        } else {
            context.startActivity(getAppDetailSettingIntent())
        }

//        }
    }

    /**
     * 获取应用详情页面intent（如果找不到要跳转的界面，也可以先把用户引导到系统设置页面）
     *
     * @return
     */
    fun getAppDetailSettingIntent(): Intent? {
        val localIntent = Intent()
        localIntent.action = "android.settings.APPLICATION_DETAILS_SETTINGS"
        localIntent.data =
            Uri.fromParts("package",App.getApp()?.packageName, null)
        return localIntent
    }

    fun Int.formatSize(): String {
        val b = this.toDouble()
        val k = this / 1024.0
        val m = this / 1024.0 / 1024.0
        val g = this / 1024.0 / 1024.0 / 1024.0
        val t = this / 1024.0 / 1024.0 / 1024.0 / 1024.0
        val dec = DecimalFormat("0.00")
        return when {
            t > 1 -> dec.format(t) + " TB"
            g > 1 -> dec.format(g) + " GB"
            m > 1 -> dec.format(m) + " MB"
            k > 1 -> dec.format(k) + " KB"
            else -> dec.format(b) + " B"
        }
    }

}
